package xin.ryven.car.android.network

import android.app.Activity
import android.content.Context
import android.util.Log
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Response
import xin.ryven.car.android.api.AuthApi
import xin.ryven.car.android.ui.LoginDialog
import xin.ryven.car.android.utils.TokenManager
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class AuthInterceptor(
    private val context: Context,
    private val authApi: AuthApi
) : Interceptor {

    companion object {
        private const val TAG = "AuthInterceptor"
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        
        // Add token to request if available
        val token = TokenManager.getToken(context)
        val newRequest = if (token != null) {
            request.newBuilder()
                .header("Authorization", "Bearer $token")
                .build()
        } else {
            request
        }

        var response = chain.proceed(newRequest)

        // Handle 403 response
        if (response.code == 403) {
            response.close() // Close the 403 response
            
            // Clear existing token
            TokenManager.clearToken(context)

            if (context is Activity) {
                // Use runBlocking because OkHttp Interceptor doesn't support suspension
                runBlocking {
                    val loginSuccess = suspendCoroutine<Boolean> { continuation ->
                        context.runOnUiThread {
                            LoginDialog(
                                context = context,
                                authApi = authApi,
                                onLoginSuccess = {
                                    continuation.resume(true)
                                }
                            ).show()
                        }
                    }

                    if (loginSuccess) {
                        // Get new token and retry request
                        val newToken = TokenManager.getToken(context)
                        if (newToken != null) {
                            val retryRequest = request.newBuilder()
                                .header("Authorization", "Bearer $newToken")
                                .build()
                            response = chain.proceed(retryRequest)
                        }
                    }
                }
            }
        }

        // Check for New-Token header and update local token if present
        val newToken = response.header("New-Token")
        if (!newToken.isNullOrEmpty()) {
            Log.d(TAG, "Received New-Token header, updating local token")
            TokenManager.saveToken(context, newToken)
            Log.d(TAG, "Local token updated successfully")
        }

        return response
    }
} 